import { ActionType, NodePlopAPI } from '@crutchcorn/plop';
import { sync } from 'glob';
import { spawnSync } from 'child_process';
import { pascalCase, camelCase, kebabCase } from 'scule';
import { resolve } from 'path';

const root = 'src/';

export default function (plop: NodePlopAPI) {
  plop.setGenerator('basics', {
    description: '这是框架文件',

    prompts: [
      {
        type: '路径',
        name: 'module',
        message: '请输入路径',
        validate: (value) => {
          if (value) return true;
          return 'module is required';
        },
      },
      {
        type: 'input',
        name: 'name',
        message: '请输入实例名',
        validate: (value) => {
          if (value) return true;
          return 'name is required';
        },
      },
    ],
    actions: (action) => {
      const { module, name } = action || {};
      const files = sync(process.cwd() + '/plop-templates/**/template.*.hbs');

      const actions: ActionType[] = files.map((file) => {
        const relativePath = file
          .replace('/plop-templates/REST', `/${module}/${kebabCase(name)}`)
          .replace('template', '{{kebabCase name}}')
          .replace('.hbs', '.ts');

        return {
          type: 'add',
          templateFile: file,
          path: relativePath,
        };
      });

      const importModule: ActionType = {
        path: resolve(process.cwd() + `/src/app.module.ts`),
        type: 'modify',
        pattern: /(import[^;]*;)(?!.*import[^;]*;)/s,
        template: `$1\nimport { {{pascalCase name}}Module } from './${kebabCase(
          module.replace(root, ''),
        )}/{{kebabCase name}}/{{kebabCase name}}.module';`,
      };
      // const b: ActionType = {
      //   // path: '{{filePath}}',
      //   path: process.cwd() + '/src/app.ts',
      //   type: 'modify',
      //   pattern: /(imports:[^[]*\[[^[\]]*?\])([,;\s]*?)(?=\s*])/,
      //   template: `$1$2, {{pascalCase name}}Module$3`,
      //   // type: 'append',
      //   // pattern: '/[Module]/',
      //   // template:
      // };

      return actions.concat([
        importModule,
        {
          type: 'after',
          // @ts-expect-error 未知类型
          paths: actions.map((v) => v.path.replace('{{kebabCase name}}', '*')),
        },
      ]);
    },
  });
  plop.setActionType('after', function (answers, config, plop) {
    const files = sync(config.paths);

    if (files) {
      spawnSync('npx', ['prettier', '--write', ...files], {
        stdio: [0, 1, 2],
      });
    }

    return 'success';
  });
}
